package com.ego.item.controller;

import com.ego.item.pojo.Category;
import com.ego.item.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @GetMapping("/list")
    public ResponseEntity<List<Category>> list(@RequestParam("pid") Long pid){
        List<Category> list = categoryService.findListByPid(pid);
        if (CollectionUtils.isEmpty(list)){
            // 返回结果集为空，响应404
            return ResponseEntity.notFound().build();
        }
        // 响应200
        return ResponseEntity.ok(list);
    }

    @GetMapping("bid/{bid}")
    public ResponseEntity<List<Category>> queryByBrandId(@PathVariable("bid") Long bid){
        List<Category> list = categoryService.queryByBrandId(bid);
        if (list == null || list.size() < 1) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        return ResponseEntity.ok(list);
    }

    @GetMapping("/list/cids")
    ResponseEntity<List<Category>> queryListByIdList(@RequestParam("cids") List<Long> categoryIdList) {
        return ResponseEntity.ok(categoryService.findListByIdList(categoryIdList));
    }

    @GetMapping("all/level/{cid3}")
    public ResponseEntity<List<Category>> queryAllCategoryLevelByCid3(@PathVariable("cid3") Long id){
        List<Category> list = categoryService.queryAllCategoryLevelByCid3(id);
        if (list == null || list.size() < 1){
            return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
        }else {
            return ResponseEntity.ok(list);
        }
    }

    @PostMapping
    public ResponseEntity<Long> save(@RequestBody Category category){
        categoryService.save(category);
        return ResponseEntity.ok(category.getId());
    }

    @PutMapping
    public ResponseEntity<Void> update(@RequestParam Long id,@RequestParam String name){
        Category category = new Category(id, name);
        categoryService.updateById(category);
        return ResponseEntity.ok().build();
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<String> delete(@PathVariable Long id){
        Category category = categoryService.findById(id);
        if (category.getIsParent()){
            return ResponseEntity.ok("不能删除父结点");
        }
        categoryService.deleteById(id);
        return ResponseEntity.ok("操作成功");
    }
}
